% Bootstrap rating history : 2008 sub-sample C
% Built connection between R and Matlab through package of Matlab Rlink. 
% Using RAndFriends on http://rcom.univie.ac.at/download.html, we install statconnDCOM.
% 
% Taking rating history of 2008 group C, we convert dataframe format into matrix 
% which is readable for Matlab. Date serial number calculation is different for
% R (start from 1970-1-1) and Matlab (0000-1-1). 
% 
% Data is now imported into Matlab and bootstrap start.
% 
% Bootstrap finish.  The replication export to R with format convert to dataframe.

clc
clear all

%% Import data from R to Matlab

status = openR;
evalR('load("D:\\My Documents\\R\\RResult\\Q_ML_grp4_08_WRcensor_8states.RData")')
evalR('mat <- matrix(unlist(newdata_4), ncol=5)') 
data = getRdata('mat');
data(:,2)= data(:,2)+datenum('1-Jan-1970');
data(:,4) = []; % removes the 2nd column
closeR;

%% Sampling with replacement to create a new data set

% Generate an index
customer = data(:,1);
lengthCus = length(customer);
cusDistinct = unique(customer);

% Use the index to create a new dataset
REP = 1;
bootDataSize = zeros(REP,1);
tic
for j = 1: REP % replication REP times
    boot_index = randsample(cusDistinct,length(cusDistinct), 'true');
    ind = [];
    for i = 1: length(boot_index)
        row = find(customer == boot_index(i));
        ind = [ind; row];
        clear row

        if length(ind)>= lengthCus 
            break 
        end    
    end
    bootDataSize(j) = length(ind);
    msg = ['boots_data',num2str(j),' Size ', num2str(bootDataSize(j))];
    disp (msg);
    bootData = data(ind,:);
    
    bootData2 = zeros(size(bootData,1), size(bootData,2));
    
    vvv = 1;
    k = 1;
    bootData2(k,:) = bootData(k,:);
    bootData2(k, 1) = vvv;
    for k = 2:length(bootData)
        c1 = bootData(k-1,1);
        c2 = bootData(k,1);
        d1 = bootData(k-1,2);
        d2 = bootData(k,2);
        if c1 == c2 && d1~=d2
        
        else
           vvv = vvv + 1; 
        end
        
        bootData2(k,:) = bootData(k,:);
        bootData2(k, 1) = vvv;
    end
       
    savefile = strcat('D:\My Documents\CIRANO\db_mySQL\bootstrap2\boot_', num2str(j),'.mat');
    save(savefile,'bootData2');
    clear boot_index bootData bootData2 ind
end

toc



%% Export data to R
%newdata.df<-as.data.frame(a[1:10,1:3]) 